package com.bwie.filter;

import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;

/**
 * @Author: 秋晚
 * @Date: 2025/7/7 15:18
 * @Description:
 **/
@Configuration
@Order(1)
public class MyFilter implements GlobalFilter {

    @Autowired
    StringRedisTemplate redisTemplate;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求和响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //白名单
        String path = request.getURI().getPath();
        if(path.contains("login")){
            return chain.filter(exchange);
        }

        //请求头token
        String token = request.getHeaders().getFirst("token");
        if(token==null){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.setComplete();
        }

        //redis中token
        Long userId = Jwts.parser().setSigningKey("bwie").parseClaimsJws(token).getBody().get("id", Long.class);
        String redisToken = redisTemplate.opsForValue().get("token-" + userId);
        if(redisToken==null){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.setComplete();
        }

        if(!token.equals(redisToken)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.setComplete();
        }

        //延期
        redisTemplate.expire("token-" + userId,15, TimeUnit.MINUTES);
        return chain.filter(exchange);
    }
}
